//
//  QRCodeViewController.m
//  QuanZiChat
//
//  Created by lanou3g on 15/11/28.
//  Copyright © 2015年 ZhongHongLin. All rights reserved.
//

#import "QRCodeViewController.h"

@interface QRCodeViewController ()
@property (weak, nonatomic) IBOutlet UILabel *userName;//账号（用于生成二维码）
@property (weak, nonatomic) IBOutlet UIImageView *qrCodeImageView;//用于显示二维码

@end

@implementation QRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    AVUser *user = [AVUser currentUser];
    self.userName.text = user.username;
    
    // Do any additional setup after loading the view.
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //-----------------------------------------------//
    AVFile *file = [[AVUser currentUser] objectForKey:@"QRCodeImage"];
    
    
    [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        
        self.qrCodeImageView.image = [UIImage imageWithData:data];
        
    
    } progressBlock:^(NSInteger percentDone) {
        
        NSLog(@"%ld", percentDone);
    }];
    //-----------------------------------------------//

}


//返回上一个界面
- (IBAction)getBackLastVC:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
//生成二维码
- (IBAction)createTheQRCode:(id)sender {
    
    self.qrCodeImageView.image = [QRCodeGenerator qrImageForString:self.userName.text imageSize:self.qrCodeImageView.frame.size.width];
    
    //获取当前用户
    AVUser *currentUser = [AVUser currentUser];
    
    //将图片转成data
    NSData *imageData = UIImagePNGRepresentation(self.qrCodeImageView.image);
    //获取data存成file
    AVFile *imageFile = [AVFile fileWithName:@"QRCodeimage.png" data:imageData];
    
    //上传文件
    [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded) {
            NSLog(@"成功");
        }else{
            NSLog(@"%@",error);
        }
        
    } progressBlock:^(NSInteger percentDone) {
        
        NSLog(@"%ld",percentDone);
    }];
    
    //将图片添加到user表中
    [currentUser setObject:imageFile forKey:@"QRCodeImage"];
    //后台保存数据
    [currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded) {
            NSLog(@"插入成功");
        }else{
            NSLog(@"%@",error);
        }
    }];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
